<?php
namespace addons\attachlink\controller;

use addons\attachlink\model\Attachlink;
use app\common\controller\AddonBase;
use app\common\model\Article;
use think\facade\Cache;
use think\App;

class Admin extends AddonBase
{

    protected $category_model;
    use \app\admin\traits\Curd;
    public function index(){
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            [$page, $limit, $where] = $this->buildTableParames();
            $model=new Attachlink();
            $count = $model->count('status');
            $list = $model
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select()->toArray();
            if(!empty($list)){
                //文章标题
                $articleTitles=(new Article())->whereIn('id',array_column($list,'subject_id'))
                    ->column('title','id');
                foreach ($list as &$v){
                    if(isset($articleTitles[$v['subject_id']])){
                        $v['subject_title']=$articleTitles[$v['subject_id']];
                    }
                }
            }
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }

        return $this->fetch();
    }
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model=new Attachlink();
    }
    public function batchAdd(){

        dd('接受定制开发，欢迎咨询QQ 278198348');
    }

    public function edit(){
        $_data=$this->request->param();
        $id=$_data['id'];
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $res=$this->model->saveData($post['attachlink']);
            if($res){
                $row1 = $this->model->find($id);
                if($row1&&isset($post['attachlink']['download_type'])){
                    $row1->download_type=$post['attachlink']['download_type'];
                    $row1->save();
                }
                $cacheName = 'attachlink_' . $row->subject .'_'.$row->subject_id;
                if (Cache::has($cacheName)) {
                    Cache::delete($cacheName);
                }
                return success('修改成功');
            }else{
                return fail('修改失败');
            }
        }
        $this->assign('attachlink',$row);
        $this->assign('k',count($row['urls']));
        return $this->fetch();
    }

}
